#include <stdio.h>
#include <string.h>
#include "socket_functions.h"
#include "json_functions.h"

// 简单的演示函数，展示JSON和Socket功能
void demo_json_functions();
void run_server_mode(int port);
void run_client_mode(const char* server_ip, int port);

int main(int argc, char* argv[]) {
    printf("Program started successfully!\n");
    printf("This program will send and receive data using JSON over Socket\n\n");
    
    // 演示JSON功能
    demo_json_functions();
    
    // 检查命令行参数，支持服务器和客户端模式
    if (argc == 3 && strcmp(argv[1], "-s") == 0) {
        // 服务器模式
        int port = atoi(argv[2]);
        printf("\n===== Starting Server Mode =====\n");
        printf("Server is listening on port %d...\n", port);
        run_server_mode(port);
    } else if (argc == 4 && strcmp(argv[1], "-c") == 0) {
        // 客户端模式
        const char* server_ip = argv[2];
        int port = atoi(argv[3]);
        printf("\n===== Starting Client Mode =====\n");
        printf("Client is connecting to server %s:%d...\n", server_ip, port);
        run_client_mode(server_ip, port);
    } else {
        // 显示使用说明
        printf("\n===== Usage Instructions =====\n");
        printf("Server mode: %s -s <port>\n", argv[0]);
        printf("Client mode: %s -c <server_ip> <port>\n", argv[0]);
        printf("\nFor example:\n");
        printf("1. Run server in first terminal: %s -s 8080\n", argv[0]);
        printf("2. Run client in second terminal: %s -c 127.0.0.1 8080\n", argv[0]);
    }
    
    printf("\nProgram ended!\n");
    
    return 0;
}

// 演示JSON功能
void demo_json_functions() {
    printf("===== JSON Functions Demo =====\n");
    
    // 创建一个简单的JSON对象
    char* json = create_json("name", "SocketJSONDemo");
    if (json != NULL) {
        printf("Created JSON: %s\n", json);
        
        // 解析JSON中的值
        char* name_value = parse_json(json, "name");
        if (name_value != NULL) {
            printf("Parsed name value: %s\n", name_value);
            free(name_value);
        } else {
            printf("Failed to parse name value\n");
        }
        
        free_json(json);
    } else {
        printf("Failed to create JSON\n");
    }
    
    // 构建Socket JSON消息
    char* socket_json = build_socket_json_message("message", "Hello from SocketJSONDemo");
    if (socket_json != NULL) {
        printf("Built Socket JSON message: %s\n", socket_json);
        
        // 解析Socket JSON消息
        char* type = NULL;
        char* data = NULL;
        if (parse_socket_json_message(socket_json, &type, &data) == 0) {
            printf("Parsed message type: %s\n", type);
            printf("Parsed message data: %s\n", data);
            free(type);
            free(data);
        } else {
            printf("Failed to parse Socket JSON message\n");
        }
        
        free_json(socket_json);
    } else {
        printf("Failed to build Socket JSON message\n");
    }
}

// 运行服务器模式
void run_server_mode(int port) {
    // 创建服务器Socket
    socket_t server_socket = create_server(port);
    if (server_socket == INVALID_SOCKET_VALUE) {
        printf("Failed to create server\n");
        return;
    }
    
    // 接受客户端连接
    printf("Waiting for client connection...\n");
    socket_t client_socket = accept_client(server_socket);
    if (client_socket == INVALID_SOCKET_VALUE) {
        printf("Failed to accept client connection\n");
        close_socket(server_socket);
        cleanup_socket();
        return;
    }
    
    // 接收客户端发送的JSON数据
    char buffer[1024];
    printf("Waiting to receive client message...\n");
    int recv_bytes = recv_data(client_socket, buffer, sizeof(buffer));
    if (recv_bytes > 0) {
        printf("Received data: %s\n", buffer);
        
        // 解析JSON消息
        char* type = NULL;
        char* data = NULL;
        if (parse_socket_json_message(buffer, &type, &data) == 0) {
            printf("Parsed message type: %s\n", type);
            printf("Parsed message data: %s\n", data);
            
            // 构建响应消息
            char* response = build_socket_json_message("response", "Message received");
            if (response != NULL) {
                // 发送响应给客户端
                send_data(client_socket, response, strlen(response));
                printf("Response sent: %s\n", response);
                free_json(response);
            }
            
            free(type);
            free(data);
        } else {
            printf("Failed to parse JSON message\n");
        }
    }
    
    // 关闭连接
    close_socket(client_socket);
    close_socket(server_socket);
    cleanup_socket();
    printf("Server closed\n");
}

// 运行客户端模式
void run_client_mode(const char* server_ip, int port) {
    // 连接到服务器
    socket_t client_socket = connect_to_server(server_ip, port);
    if (client_socket == INVALID_SOCKET_VALUE) {
        printf("Failed to connect to server\n");
        return;
    }
    
    // 构建要发送的JSON消息
    char* json_message = build_socket_json_message("message", "Hello from Client!");
    if (json_message == NULL) {
        printf("Failed to build JSON message\n");
        close_socket(client_socket);
        cleanup_socket();
        return;
    }
    
    // 发送JSON消息
    printf("Sending message: %s\n", json_message);
    int sent_bytes = send_data(client_socket, json_message, strlen(json_message));
    if (sent_bytes > 0) {
        printf("Successfully sent %d bytes\n", sent_bytes);
        
        // 等待接收服务器响应
        char buffer[1024];
        printf("Waiting to receive server response...\n");
        int recv_bytes = recv_data(client_socket, buffer, sizeof(buffer));
        if (recv_bytes > 0) {
            printf("Received response: %s\n", buffer);
            
            // 解析响应消息
            char* type = NULL;
            char* data = NULL;
            if (parse_socket_json_message(buffer, &type, &data) == 0) {
                printf("Parsed response type: %s\n", type);
                printf("Parsed response data: %s\n", data);
                free(type);
                free(data);
            } else {
                printf("Failed to parse response message\n");
            }
        }
    }
    
    // 清理资源
    free_json(json_message);
    close_socket(client_socket);
    cleanup_socket();
    printf("Client closed\n");
}